﻿/*    
Nemulation: A .NET based framework/platform for virtualization applications
Copyright (C) 2011 Bryan Perris

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using NEmu.Debugging;
using System.Security;
using System.Globalization;

namespace NEmu.Utilities
{
    public static class SaveStateManager
    {
        public static readonly string STATE_FILE_NAME = "state";
        static string s_StateFilePath = "./states/";

        public static void SaveState<TVirtualMachine>(TVirtualMachine machine, int slotNumber) where TVirtualMachine : VirtualMachine
        {
            string filepath = s_StateFilePath + "\\" + STATE_FILE_NAME + slotNumber.ToString(CultureInfo.CurrentCulture);
            EmuLog.DebugLog("Savestate Path: " + filepath);

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(filepath)))
                    Directory.CreateDirectory(filepath);

                FileStream file = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read);
                BinaryFormatter formatter = new BinaryFormatter();

                try
                {
                    formatter.Serialize(file, machine);
                }
                catch (SerializationException e)
                {
                    EmuLog.WarningLog("failed to save state: " + e.Message);
                }

                file.Close();
            }
            catch (UnauthorizedAccessException)
            {
                EmuLog.ErrorLog("Savestate Write Error: no permissions to access this file or write path!");
            }
            catch (SecurityException)
            {
                EmuLog.ErrorLog("Savestate Write Error: need permissions to overwrite file!");
            }
            catch (DirectoryNotFoundException)
            {
                EmuLog.ErrorLog("Savestate Write Error: can't find specified directory path");
            }
            catch (IOException)
            {
                throw new VMException("file I/O error while writing savestate");
            }
            catch (ArgumentException)
            {
                throw new VMException("The filepath is invalid: " + filepath);
            }
        }

        public static TVirtualMachine LoadState<TVirtualMachine>(int slotNumber) where TVirtualMachine : VirtualMachine
        {
            string filepath = s_StateFilePath + "\\" + STATE_FILE_NAME + slotNumber.ToString(CultureInfo.CurrentCulture);
            EmuLog.DebugLog("Savestate Path: " + filepath);
            TVirtualMachine machine = null;

            try
            {
                FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryFormatter formatter = new BinaryFormatter();

                try
                {
                   machine = (TVirtualMachine)formatter.Deserialize(file);
                }
                catch (SerializationException e)
                {
                    EmuLog.WarningLog("Failed to load state: " + e.Message);
                }

                file.Close();

                return machine;
            }

            catch (ArgumentException)
            {
                throw new VMException("The filepath is invalid: " + filepath);
            }
            catch (FileNotFoundException)
            {
                EmuLog.WarningLog("Savestate Read Error: file not found");
            }
            catch (UnauthorizedAccessException)
            {
                EmuLog.ErrorLog("Savestate Write Error: no permissions to access this file or read path!");
            }
            catch (SecurityException)
            {
                EmuLog.ErrorLog("Savestate Read Error: need permissions to overwrite file!");
            }
            catch (DirectoryNotFoundException)
            {
                EmuLog.ErrorLog("Savestate Read Error: can't find specified directory path");
            }
            catch (IOException)
            {
                throw new VMException("file I/O error while writing savestate");
            }

            return null;
        }

        public static void DeleteSaveState(int slotNumber)
        {
            try
            {
                File.Delete(s_StateFilePath + "\\" + STATE_FILE_NAME + slotNumber.ToString(CultureInfo.CurrentCulture));
            }
            catch (SecurityException)
            {
                return;
            }
            catch (FileNotFoundException)
            {
                return;
            }
            catch (IOException)
            {
                return;
            }
        }

        public static string SaveStatePath
        {
            get { return s_StateFilePath; }
            set { s_StateFilePath = value; }
        }
    }
}
